package com.qcby.domain.login.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.qcby.domain.login.model.entity.Captcha;
import com.qcby.domain.login.service.ILoginService;
import com.qcby.types.common.CacheConstants;
import com.qcby.types.exception.BusinessException;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import com.google.code.kaptcha.Producer;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author cong.zhen
 * @date 2024/07/19
 */
@Service
public class LoginServiceImpl implements ILoginService {

    /**
     * 验证码有效期（分钟）
     */
    private static final Integer CAPTCHA_EXPIRATION = 2;

    @Resource
    private Producer captchaProducer;

    @Resource
    private RedissonClient redissonClient;

    @Override
    public Captcha getCode() {
        String uuid = IdUtil.fastUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(capStr);
        //将验证码存入到redis中，有效期为两分钟
        redissonClient.getBucket(verifyKey).set(capStr,CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            //将生成的表达式转换成图片
            ImageIO.write(image, "jpg", os);
        }catch (IOException e){
            throw  new BusinessException("访问太频繁，请稍后再试");
        }
        Captcha captchaVO = new Captcha();
        captchaVO.setImg(Base64.encode(os.toByteArray()));
        captchaVO.setUuid(uuid);
        return captchaVO;
    }
}
